package cn.rwklyd.BookKeeping.handler;
import cn.rwklyd.BookKeeping.constant.MessageConstant;
import cn.rwklyd.BookKeeping.exception.BaseException;
import cn.rwklyd.BookKeeping.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.sql.SQLIntegrityConstraintViolationException;
import org.springframework.security.authentication.BadCredentialsException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */

@RestControllerAdvice  // 表示该类是一个异常处理器
@Slf4j
public class GlobalExceptionHandler {

/**
     * 捕获业务异常
     * @param ex
     * @return
     */

    @ExceptionHandler(BaseException.class)
    public Result handleBaseException(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

/**
     * 处理登录密码错误异常
     * @param ex
     * @return
     */

    @ExceptionHandler(BadCredentialsException.class)
    public Result handleBadCredentialsException(BadCredentialsException ex){
        log.error("密码错误：{}", ex.getMessage());
        return Result.error(MessageConstant.PASSWORD_ERROR);
    }

/**
     * 处理SQL异常
     * @param ex
     * @return
     */

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result handleSQLException(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){   // 判断是否是唯一性异常
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }else{
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }
}

